<template>
  <div class='container'>
    <el-card class="box-card">
  <div slot="header" class="clearfix">
    <span>试题录入</span>
  </div>
  <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm" >
  <el-form-item label="学科:" prop="subjectID" >
   <el-select  placeholder="请选择" style="width:400px" v-model="ruleForm.subjectID" @change="getdirectoryslist">
      <el-option :label="item.label" :value="item.value" v-for="item in subjectOptions" :key="item.value"></el-option>
    </el-select>
  </el-form-item>
  <el-form-item label="目录:" prop="catalogID">
    <el-select  placeholder="请选择" style="width:400px" v-model="ruleForm.catalogID">
      <el-option :label="item.label" :value="item.value" v-for="item in catalogOptions" :key="item.value"></el-option>
    </el-select>
  </el-form-item>
  <el-form-item label="企业:" prop="enterpriseID">
    <el-select  placeholder="请选择" style="width:400px" v-model="ruleForm.enterpriseID">
      <el-option :label="item.company" :value="item.id" v-for="item in enterpriseOptions" :key="item.id" ></el-option>
    </el-select>
  </el-form-item>
  <el-form-item label="城市:" prop="city">
    <el-select  placeholder="请选择" style="width:200px" v-model="ruleForm.province" @change="getcitylist">
      <el-option :label="item" :value="item" v-for="(item,index) in provincesoptions" :key="index"></el-option>
    </el-select>
    <el-select  placeholder="请选择" style="width:200px" v-model="ruleForm.city">
      <el-option :label="item" :value="item" v-for="(item,index) in citysoption" :key="index"></el-option>
    </el-select>
  </el-form-item>
  <el-form-item label="方向:" prop="direction">
    <el-select  placeholder="请选择" style="width:400px" v-model="ruleForm.direction" >
      <el-option :label="item" :value="item" v-for="item in directionoption" :key="item"></el-option>
    </el-select>
  </el-form-item>
   <el-form-item label="题型:" prop="questionType">
    <el-radio-group v-model="ruleForm.questionType">
      <el-radio :label="item.value+''"  v-for="item in questionTypeoption" :key="item.value">
        <template>
          {{item.label}}
        </template>
      </el-radio>
    </el-radio-group>
  </el-form-item>
   <el-form-item label="难度:" prop="questionType" >
    <el-radio-group v-model="ruleForm.difficulty">
       <el-radio :label="item.value+''"  v-for="item in difficultyoption" :key="item.value">
        <template>
          {{item.label}}
        </template>
      </el-radio>
    </el-radio-group>
  </el-form-item>
  <el-form-item label="题干:" prop="question" >
   <quill-editor :options="editorOptions" style="height:200px;margin-bottom:50px" v-model="ruleForm.question"></quill-editor>
  </el-form-item>
  <el-form-item label="选项:" v-if="ruleForm.questionType!=='3'">
      <div class="option-letter" v-for="item in ruleForm.options" :key="item.code" style="margin-bottom:10px">

        <el-radio :label="true"  v-model="item.isRight" v-if="ruleForm.questionType==='1'" @change="getradio(item)">{{item.code}}:</el-radio>
        <el-checkbox v-if="ruleForm.questionType==='2'" v-model="item.isRight" :label="true">{{item.code}}:</el-checkbox>
        <el-input v-model="item.title"></el-input>
        <el-upload
          action="#"
          :limit="1"
          list-type="picture-card"
          :http-request="(obj)=>{httprequest(item,obj)}"
          :class="{myupload:item.img}"
          :on-remove="(file, fileList)=>{handleRemove(item,file, fileList)}">
          上传图片
        </el-upload>
      </div>
   <el-button type="danger" :disabled="ruleForm.questionType!=='2'" @click="addOption">+增加选项与答案</el-button>
  </el-form-item>
    <el-form-item label="解析视频">
       <el-input v-model="ruleForm.videoURL"></el-input>
    </el-form-item>
    <el-form-item label="答案解析:" prop="answer">
   <quill-editor :options="editorOptions" style="height:200px;margin-bottom:50px" v-model="ruleForm.answer"></quill-editor>
  </el-form-item>
  <el-form-item label="题目备注:">
    <el-input type="textarea" v-model="ruleForm.remarks"></el-input>
  </el-form-item>
  <el-form-item label="试题标签:">
    <el-select
    placeholder="请选择"
    style="width:400px"
    v-model="ruleForm.tags"
    multiple
    filterable
    allow-create
    default-first-option>
      <el-option :label="item.label" :value="item.label" v-for="item in tagsOptions" :key="item.value"></el-option>
    </el-select>
  </el-form-item>
  <el-form-item>
    <el-button type="primary" @click="submitForm('ruleForm')">{{$route.query.id?'确认修改':'确认提交'}}</el-button>
    <!-- <el-button @click="resetForm('ruleForm')">重置</el-button> -->
  </el-form-item>
</el-form>
</el-card>
  </div>
</template>

<script>
import { add, detail, update } from '@/api/hmmm/questions.js'
// 标签
import { simple as tagslist } from '@/api/hmmm/tags.js'
// 方向
import { direction, questionType, difficulty } from '@/api/hmmm/constants.js'
// 获取城市和城市下地区
import { provinces, citys } from '@/api/hmmm/citys.js'
// 企业列表
import { list as companyslist } from '@/api/hmmm/companys.js'
// 简单目录列表
import { simple as directoryslist } from '@/api/hmmm/directorys.js'
// 学科列表
import { simple as getsimple } from '@/api/hmmm/subjects.js'
import { quillEditor } from 'vue-quill-editor'
// 导入富文本编辑器样式
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
var COS = require('cos-js-sdk-v5')

// SECRETID 和 SECRETKEY请登录 https://console.cloud.tencent.com/cam/capi 进行查看和管理
var cos = new COS({
  SecretId: 'AKIDhHgrshQzNYVItHRj6GE0by86sRl3GI7j',
  SecretKey: 'TnvtiMsAIF1e6f7OR6buAOTM2WotmbDe'
})
export default {
  name: 'new',
  components: {
    quillEditor
  },
  data () {
    return {
      url: '',
      dialogVisible: false,
      editorOptions: {
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'],
            [{ list: 'ordered' }, { list: 'bullet' }],
            ['blockquote'],
            ['code-block', 'image', 'link']
          ]
        }
      },
      // 学科选项
      subjectOptions: [],
      // 目录选项
      catalogOptions: [],
      // 企业选项
      enterpriseOptions: [],
      // 城市
      provincesoptions: provinces(),
      // 地区
      citysoption: [],
      // 方向
      directionoption: direction,
      // 题型
      questionTypeoption: questionType,
      // 难度
      difficultyoption: difficulty,
      // 标签
      tagsOptions: [],
      ruleForm: {
        subjectID: null,
        catalogID: null,
        enterpriseID: null,
        // 城市
        province: null,
        // 地区
        city: null,
        // 方向
        direction: null,
        // 题型
        questionType: '1',
        // 难度
        difficulty: '1',
        // 题干
        question: null,
        // 选项
        options: [
          { isRight: false, code: 'A', title: '', img: '' },
          { isRight: false, code: 'B', title: '', img: '' },
          { isRight: false, code: 'C', title: '', img: '' },
          { isRight: false, code: 'D', title: '', img: '' }
        ],
        // 视频
        videoURL: null,
        // 答案解析
        answer: null,
        // 备注
        remarks: null,
        // 标签
        tags: null

      },
      rules: {
        subjectID: [
          { required: true, message: '请选择学科', trigger: 'change' }
        ],
        catalogID: [
          { required: true, message: '请选择目录', trigger: 'change' }
        ],
        enterpriseID: [
          { required: true, message: '请选择企业', trigger: 'change' }
        ],
        city: [
          { required: true, message: '请选择地区', trigger: 'change' }
        ],
        direction: [
          { required: true, message: '请选择方向', trigger: 'change' }
        ],
        questionType: [
          { required: true, message: '请选择题型', trigger: 'change' }
        ],
        difficulty: [
          { required: true, message: '请选择难度', trigger: 'change' }
        ],
        question: [
          { required: true, message: '请输入题干', trigger: 'blur' }
        ],
        answer: [
          { required: true, message: '请输入题干', trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    if (this.$route.query.id) {
      this.getdetaillist(this.$route.query)
    }
    this.getsimplelist()
    this.getcompanyslist()
  },
  methods: {
    // 添加选项
    addOption () {
      this.ruleForm.options.push({
        isRight: false,
        code: String.fromCharCode(65 + this.ruleForm.options.length),
        title: '',
        img: ''
      })
    },
    // 获取题库详情
    async getdetaillist (id) {
      const { data } = await detail(id)
      console.log(data)
      console.log(data.tags)
      data.tags = data.tags.split(',')
      data.options = data.options.map(item => {
        item.isRight = item.isRight === 1
        return item
      })
      // data.tags = data.tags.map(item => +item)
      console.log(data.tags)
      this.ruleForm = data
      console.log(this.ruleForm)
      const { data: res } = await directoryslist({ subjectID: this.ruleForm.subjectID })
      this.catalogOptions = res
      const { data: res2 } = await tagslist({ subjectID: this.ruleForm.subjectID })
      this.tagsOptions = res2
      console.log(this.ruleForm.tags)
      console.log(this.tagsOptions)
    },
    handleRemove (item, file, fileList) {
      item.img = ''
    },
    // 获标签
    // async gettagslist () {
    //   const { data } = await tagslist({ subjectID: this.ruleForm.subjectID })
    //   this.tagsOptions = data
    // },
    // 覆盖默认的上传行为，保证上传文件不会消失
    httprequest (item, obj) {
      // obj.file为文件对象 等于files[0]
      console.log(obj.file)
      cos.putObject({
        Bucket: 'hrsass-1309373845', /* 必须 */
        Region: 'ap-shanghai', /* 存储桶所在地域，必须字段 */
        Key: +new Date() + obj.file.name, /* 必须 唯一值，必须是字符串 */
        StorageClass: 'STANDARD',
        Body: obj.file, // 上传文件对象0
        onProgress: (progressData) => {
          console.log(1)
          console.log(+new Date())
          console.log(JSON.stringify(progressData))
        }
      }, function (err, data) {
        console.log(2)
        console.log(err || data)
        item.img = 'http://' + data.Location
      })
    },
    // 获取城市下地区
    getcitylist () {
      this.ruleForm.city = null
      this.citysoption = citys(this.ruleForm.province)
    },
    // 获取企业列表
    async getcompanyslist () {
      const { data } = await companyslist()
      console.log(data)
      this.enterpriseOptions = data.items
    },
    // 获取简单目录
    async getdirectoryslist () {
      console.log(this.ruleForm.subjectID)
      // this.ruleForm.catalogID = null
      const { data } = await directoryslist({ subjectID: this.ruleForm.subjectID })
      // console.log(data)
      this.catalogOptions = data
      this.ruleForm.tags = null
      const { data: res } = await tagslist({ subjectID: this.ruleForm.subjectID })
      this.tagsOptions = res
    },
    // 获取学科简单列表
    async getsimplelist () {
      const { data } = await getsimple()
      // console.log(data)
      this.subjectOptions = data
    },
    submitForm () {
      this.$refs.ruleForm.validate(async (boo) => {
        if (!boo) return 1
        if (!this.$route.query.id) {
          const nmb = { ...this.ruleForm }
          nmb.tags = nmb.tags.join(',')
          await add(nmb)
          this.$router.push('/questions/list')
          this.$message.success('修改成功')
          this.$refs.ruleForm.resetFields()
        } else {
          const nmb = { ...this.ruleForm }
          nmb.tags = nmb.tags.join(',')
          await update(nmb)
          this.$router.push('/questions/list')
          this.$message.success('提交成功')
          this.$refs.ruleForm.resetFields()
        }
      })
    },
    resetForm (formName) {
      this.$refs[formName].resetFields()
    },
    getradio (item) {
      this.ruleForm.options.forEach(item => {
        item.isRight = false
      })
      console.log(item)
      item.isRight = true
    }
  }
  // 单选的时候
  // computed: {
  //   isshow () {
  //     return this.ruleForm.options.img
  //   }
  // }
}
</script>

<style scoped lang="scss">
.container{
  margin: 20px;
}
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  .option-letter{
    width: 400px;
    display: flex;
    align-items: center;
  }
::v-deep .el-upload{
    width: 100px;
    height: 60px;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  ::v-deep .el-upload-list--picture-card .el-upload-list__item{
      width: 100px;
  height: 60px;
  display: block;
  overflow: hidden;
  }
.myupload {
  ::v-deep.el-upload--picture-card {
    display: none;
  }
}
</style>
